package com.getan.boot.module.system.controller;

import com.getan.boot.common.ResponseBuilder;
import com.getan.boot.common.ResponseCodeData;
import com.getan.boot.common.annotation.OperateLog;
import com.getan.boot.common.domain.bo.IdBO;
import com.getan.boot.module.system.domain.bo.DeptBO;
import com.getan.boot.module.system.entity.DeptEntity;
import com.getan.boot.module.system.service.persistent.DeptService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * 部门管理
 *
 * @author Bruce.Gong
 * @since 1.0.0-SNAPSHOT
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/dept")
public class DeptController {

    private final String MODULE = "部门管理";
    private final DeptService deptService;

    @PostMapping("tree")
    public ResponseCodeData<List<DeptEntity>> tree() {
        return ResponseBuilder.ok(deptService.tree());
    }

    @OperateLog(module = MODULE, businessType = "ADD")
    @PostMapping("add")
    public ResponseCodeData<Long> add(@RequestBody @Valid DeptBO.AddBO bo) {
        DeptEntity entity = new DeptEntity();
        BeanUtils.copyProperties(bo, entity);
        deptService.checkParentActive(entity.getPid());
        deptService.checkName(entity);
        deptService.insert(entity);
        return ResponseBuilder.ok(entity.getId());
    }

    @OperateLog(module = MODULE, businessType = "UPDATE")
    @PostMapping("update")
    public ResponseCodeData<Long> update(@RequestBody @Valid DeptBO.UpdateBO bo) {
        DeptEntity entity = new DeptEntity();
        BeanUtils.copyProperties(bo, entity);
        deptService.canUpdate(entity);
        deptService.update(entity);
        return ResponseBuilder.ok(entity.getId());
    }

    @OperateLog(module = MODULE, businessType = "DELETE")
    @PostMapping("delete")
    public ResponseCodeData<Void> delete(@RequestBody @Valid IdBO bo) {
        DeptEntity db = deptService.canDelete(bo.getId());
        deptService.delete(db.getId());
        return ResponseBuilder.ok();
    }

    @OperateLog(module = MODULE, businessType = "DISABLE")
    @PostMapping("disable")
    public ResponseCodeData<Void> disable(@RequestBody @Valid IdBO bo) {
        DeptEntity db = deptService.canDisable(bo.getId());
        deptService.disable(db.getId());
        return ResponseBuilder.ok();
    }

    @OperateLog(module = MODULE, businessType = "ENABLE")
    @PostMapping("enable")
    public ResponseCodeData<Void> enable(@RequestBody @Valid IdBO bo) {
        DeptEntity db = deptService.canEnable(bo.getId());
        deptService.enable(db.getId());
        return ResponseBuilder.ok();
    }

}
